package org.catspaw.cherubim.persistence.dao.jdbc;

import java.util.List;
import java.util.Map;
import org.catspaw.cherubim.persistence.dao.SearchDao;
import org.catspaw.cherubim.persistence.jdbc.DefaultConnectionManager;
import org.catspaw.cherubim.persistence.jdbc.dbutils.SqlExecutor;
import org.catspaw.cherubim.util.GenericTypeUtils;

public class SearchJdbcDao implements SearchDao {

	private Class<?>	entityClass;
	private SqlExecutor	executor;

	public SearchJdbcDao(Class<?> entityClass, SqlExecutor executor) {
		this.entityClass = entityClass;
		this.executor = executor;
	}

	public SearchJdbcDao(Class<?> entityClass) {
		this(entityClass, new SqlExecutor(new DefaultConnectionManager()));
	}

	public SearchJdbcDao(SqlExecutor executor) {
		this.executor = executor;
	}

	protected Class<?> getEntityClass() {
		if (entityClass == null) {
			entityClass = (Class<?>) GenericTypeUtils
					.getSuperClassGenericType(this.getClass());
		}
		return entityClass;
	}

	public Object findOne(String sql, Object... params) {
		List<?> list = findList(sql, -1, -1, null, params);
		if (!list.isEmpty()) {
			return list.get(0);
		}
		return null;
	}

	public Object findOne(String queryString, Map<String, ?> params) {
		throw new UnsupportedOperationException("not support named parameter");
	}

	public List<?> findList(String sql, Map<String, ?> params) {
		throw new UnsupportedOperationException("not support named parameter");
	}

	public List<?> findList(String sql, Object... params) {
		return findList(sql, -1, -1, null, params);
	}

	public List<?> findList(String sql, int offset, int max,
			Map<String, ?> params) {
		throw new UnsupportedOperationException("not support named parameter");
	}

	public List<?> findList(String sql, int offset, int max, Object... params) {
		return findList(sql, -1, -1, null, params);
	}

	public SqlExecutor getSqlExecutor() {
		return executor;
	}
}
